package com.example.composerecompose.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material3.Icon
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.example.composerecompose.screens.shared.Screen
import com.example.composerecompose.screens.shared.TopBar

class Contact(name: String){
    var name by mutableStateOf(name)

    override fun equals(other: Any?): Boolean {
        return name == other
    }

}

//@Stable
//data class Contact(var name: String)

/**
 *
 * 由于 Contact 对象中有 name是 var的，编译器会认为你是不稳定的
 * 有下面 2 中优化方法
 *
 * 1: 添加 @Stable 注解
 * @Stable
 * data class Contact(var name: String)
 *
 *
 *2: 去掉data(不过最好实现 equals) 然后去掉 var  并添加mutableStateOf来缓存值
 * class Contact(name: String){
 *     var name by mutableStateOf(name)
 *
 *     override fun equals(other: Any?): Boolean {
 *         return name == other
 *     }
 * }
 *
 */

@Composable
fun StableState() {
    Screen {
        Scaffold(
            topBar = { TopBar("Stable State") }
        ) { padding ->

            val contact = remember { Contact("John Doe") }
            var selected by remember { mutableStateOf(false) }

            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                ContactDetail(contact)
                ToggleHeart(
                    checked = selected,
                    onCheckedChange = { selected = it }
                )
            }

        }
    }

}

@Composable
private fun ContactDetail(contact: Contact) {
    Text(
        text = contact.name,
        style = MaterialTheme.typography.headlineSmall
    )
}

@Composable
fun ToggleHeart(checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
    IconToggleButton(checked, onCheckedChange) {
        Icon(
            imageVector = if (checked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
            contentDescription = "Favorite"
        )
    }
}
